package com.zyk.scaffold.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.zyk.scaffold.common.exception.BusinessException;
import com.zyk.scaffold.common.utils.MapUtils;
import com.zyk.scaffold.common.utils.StringUtils;
import com.zyk.scaffold.gateway.constant.GatewayConstants;
import com.zyk.scaffold.gateway.enums.GatewayErrorCodeEnum;
import com.zyk.scaffold.gateway.properties.LocalGatewayProperties;
import com.zyk.scaffold.gateway.service.TokenService;
import com.zyk.scaffold.oauth.dto.TokenInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

@Slf4j
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private LocalGatewayProperties localGatewayProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // openApi 放过
        if (exchange.getAttributeOrDefault(GatewayConstants.OPEN_API_KEY_AUTH, Boolean.FALSE)) {
            return chain.filter(exchange);
        }

        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getRawPath();
        log.info("AuthenticationFilter. url: {}", uri);
        // 开放接口
        if (isPublicPath(uri)) {
            return chain.filter(exchange);
        }
        // swagger接口
        if (isSwaggerPath(uri)) {
            return chain.filter(exchange);
        }
        // 获取token
        String accessToken = parseAccessToken(request);
        if (StringUtils.isEmpty(accessToken)) {
            log.error("access-token is emtpy. url: {},headers:{}", request.getURI(), JSON.toJSONString(request.getHeaders()));
            throw new BusinessException(GatewayErrorCodeEnum.TOKEN_INVALID_ERROR);
        }
        // 解析token
        TokenInfoDTO tokenInfo = tokenService.analysisAccessToken(accessToken);
        if(!validTokenInfo(tokenInfo)){
            throw new BusinessException(GatewayErrorCodeEnum.TOKEN_INVALID_ERROR);
        }
        // 内部开放接口
        if (isInnerPublicPath(uri)) {
            return buildChainFilter(chain, exchange, tokenInfo);
        }
        // api校验
        if(!validMenuApis(tokenInfo.getMenuApis(), uri)){
            throw new BusinessException(GatewayErrorCodeEnum.REQUEST_ULTRA_VIRES_ERROR);
        }
        return buildChainFilter(chain, exchange, tokenInfo);
    }

    // 设置 userId, 用户信息
    private Mono<Void> buildChainFilter(GatewayFilterChain chain, ServerWebExchange exchange, TokenInfoDTO tokenInfo) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder requestBuilder = request.mutate();
        requestBuilder.headers(httpHeaders -> {
            httpHeaders.remove(GatewayConstants.GATEWAY_FILTER_HEADER_USER_ID);
            httpHeaders.remove(GatewayConstants.GATEWAY_FILTER_HEADER_TENANT_CODE);
            httpHeaders.remove(GatewayConstants.GATEWAY_FILTER_HEADER_JWT_USER_METADATA);
        });
        requestBuilder.header(GatewayConstants.GATEWAY_FILTER_HEADER_USER_ID, StringUtils.toString(tokenInfo.getUserId()));
        requestBuilder.header(GatewayConstants.GATEWAY_FILTER_HEADER_JWT_USER_METADATA, tokenInfo.getJwt());
        requestBuilder.header(GatewayConstants.GATEWAY_FILTER_HEADER_TENANT_CODE, tokenInfo.getTenantCode());
        return chain.filter(exchange.mutate().request(requestBuilder.build()).build());
    }

    private String parseAccessToken(ServerHttpRequest request) {
        String accessToken = request.getQueryParams().getFirst(GatewayConstants.GATEWAY_FILTER_ACCESS_TOKEN_NAME);
        return StringUtils.isEmpty(accessToken) ? request.getHeaders().getFirst(GatewayConstants.GATEWAY_FILTER_ACCESS_TOKEN_NAME) : accessToken;
    }

    private boolean validMenuApis(List<Map<String, Object>> menuApis, String uri) {
        return menuApis.stream().map(menuApisItem -> MapUtils.getHashSet(menuApisItem, "apis", String.class, Collections.emptySet()))
                .anyMatch(item -> {
                    for (String regexUrl : item) {
                        if (Pattern.matches(regexUrl, uri)) {
                            return true;
                        }
                    }
                    return false;
                });
    }

    private boolean validTokenInfo(TokenInfoDTO tokenInfo) {
        if(tokenInfo == null){
            return Boolean.FALSE;
        }
        if(Objects.isNull(tokenInfo.getUserId())){
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    public int getOrder() {
        return -50;
    }

    private boolean isPublicPath(String uri) {
        return localGatewayProperties.getApi().getPublicPath().contains(uri);
    }

    private boolean isInnerPublicPath(String uri) {
        return localGatewayProperties.getApi().getInnerPublicPath().contains(uri);
    }
    private boolean isSwaggerPath(String uri) {
        if(localGatewayProperties.getTest()){
            for (String regexUrl : localGatewayProperties.getApi().getSwaggerPath()) {
                if (Pattern.matches(regexUrl, uri)) {
                    return true;
                }
            }
        }
        return false;
    }
}
